﻿using System;

namespace Sail.Caching
{
    /// <summary>
    /// 提供一个缓存管理得默认实现，缓存管理提供一个抽象的缓存持有者去很容易的在各个组件上下文进行缓存的交换和独立
    /// </summary>
    public class DefaultCacheManager : ICacheManager
    {
        private readonly Type _component;
        private readonly ICacheHolder _cacheHolder;

        /// <summary>
        /// 构造函数，初始化
        /// </summary>
        /// <param name="component">组件</param>
        /// <param name="cacheHolder">缓存持有者</param>
        public DefaultCacheManager(Type component, ICacheHolder cacheHolder)
        {
            _component = component;
            _cacheHolder = cacheHolder;
        }

        /// <summary>
        /// 从缓存持有者获取缓存实体
        /// </summary>
        /// <typeparam name="TKey">缓存键</typeparam>
        /// <typeparam name="TResult">缓存值</typeparam>
        /// <returns>缓存实体</returns>
        public ICache<TKey, TResult> GetCache<TKey, TResult>()
        {
            return _cacheHolder.GetCache<TKey, TResult>(_component);
        }

        public TResult Get<TKey, TResult>(TKey key, Func<AcquireContext<TKey>, TResult> acquire)
        {
            return GetCache<TKey, TResult>().Get(key, acquire);
        }
    }
}